package cn.ryh.designpatterndemo.proxypattern.cglibproxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ClassName CglibProxyFactroy
 * @Description TODO
 * @Author RaoYH
 * @Date 2019/4/23
 */
public class CglibProxyFactroy implements MethodInterceptor {
    // 被代理者(目标对象)
    private Object target ;
    // 通过有参构造函数传递要对谁进行代理
    public CglibProxyFactroy(Object target) {
        this.target = target;
    }

    //为目标对象生成代理对象
    public Object getProxyInstance() {
        //工具类
        Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(target.getClass());
        //设置回调函数
        en.setCallback(this);
        //创建子类对象代理
        return en.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        this.before();
        // 执行目标对象方法
        Object returnValue = method.invoke(target, objects);
        this.after();
        return null;
    }


    // 前置处理
    private void before() {
        System.out.println("--->前置处理：do something");

    }

    // 后置处理
    private void after() {
        System.out.println("--->后置处理：do something");
    }
}
